
const version = process.version;
const { error } = require('./log');
const versionEngines = enginesJSON();
const { node, limitMin } = versionEngines;


if (versionStringCompare(version, limitMin, 0) === -1) {
  error(`===================================\r\n
  当前node版本为： ${version} ，本项目要求node版本为：${versionEngines.node}，建议为：${versionEngines.suggestions}
  \r\n=====================================`);
  process.exit(1);
}


/*
 * 获取node版本
 * @returns
 */
function enginesJSON() {
  try {
    const path = require('path');
    const { engines,suggestions,limitMin } = require(path.join(process.cwd(), 'package.json'))
    return { node: engines.node, suggestions,limitMin };
  } catch (error) {
    return {
      node: '>=18.14.1',
      suggestions: 'v18.x',
      limitMin: '18.14.1'
    };
  }
}

// 版本号比较
function versionStringCompare(preVersion, lastVersion, nex) {
  if (!lastVersion) {
    return 0;
  }
  const sources = preVersion.replace("v", "").replace("x", nex === 0 ? "0" : "9").split('.');
  const dests = lastVersion.replace("v", "").replace("x", nex === 0 ? "0" : "9").split('.');
  const maxL = Math.max(sources.length, dests.length);
  let result = 0;
  for (let i = 0; i < maxL; i++) {
    let preValue = sources.length > i ? sources[i] : 0;
    let preNum = isNaN(Number(preValue)) ? preValue.charCodeAt() : Number(preValue);
    let lastValue = dests.length > i ? dests[i] : 0;
    let lastNum = isNaN(Number(lastValue)) ? lastValue.charCodeAt() : Number(lastValue);
    if (preNum < lastNum) {
      result = -1;
      break;
    } else if (preNum > lastNum) {
      result = 1;
      break;
    }
  }
  return result;
}